package com.wanghlme.leetcodecn;

/**
 * <p>剑指 Offer 53 - I. 在排序数组中查找数字 I</p>
 * <p>JZ53-main0034</p>
 *
 * @author wanghlme
 * @version 1.0
 */
public class LC_JZ53 {
    public static void main(String[] args) {
        System.out.println(new Solution().search(new int[]{5, 7, 7, 8, 8, 10}, 8));
    }

    static class Solution {
        public int search(int[] nums, int target) {
            int leftIdx = binarySearch(nums, target, true);
            int rightIdx = binarySearch(nums, target, false) - 1;
            if (leftIdx <= rightIdx && rightIdx < nums.length && nums[leftIdx] == target && nums[rightIdx] == target) {
                return rightIdx - leftIdx + 1;
            }
            return 0;
        }

        public int binarySearch(int[] nums, int target, boolean lower) {
            int left = 0, right = nums.length - 1, ans = nums.length;
            while (left <= right) {
                int mid = (left + right) / 2;
                if (nums[mid] > target || (lower && nums[mid] >= target)) {
                    right = mid - 1;
                    ans = mid;
                } else {
                    left = mid + 1;
                }
            }
            return ans;
        }
    }
}
